package sk.stuba.fiit.repka.dp.gui;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

import org.apache.log4j.Logger;
import org.semanticweb.owlapi.model.OWLOntologyCreationException;
import org.semanticweb.owlapi.model.OWLOntologyStorageException;

import sk.stuba.fiit.repka.dp.db.AttributesMapper;
import sk.stuba.fiit.repka.dp.db.DBAttributesManipulator;
import sk.stuba.fiit.repka.dp.db.DBExpectationsManipulator;
import sk.stuba.fiit.repka.dp.db.DataManipulator;
import sk.stuba.fiit.repka.dp.db.DatabaseController;
import sk.stuba.fiit.repka.dp.db.EnumUtils;
import sk.stuba.fiit.repka.dp.owl.MyOWLClass;
import sk.stuba.fiit.repka.dp.owl.MyOWLDataProperty;
import sk.stuba.fiit.repka.dp.owl.MyOWLIndividual;
import sk.stuba.fiit.repka.dp.owl.MyOWLObjectProperty;
import sk.stuba.fiit.repka.dp.owl.OWLCreationManager;
import sk.stuba.fiit.repka.dp.owl.gui.MainPanel;

public class MainWindow implements ActionListener{
	private static Logger logger = Logger.getLogger(MainWindow.class);
	
	private JFrame frmWebServiceRequirements;
	
	private MainPanel mainPanel;
	private DatabaseController dbController;
	
	private String onotoName;
	
	public String getOntoName() {
		return this.onotoName;
	}
	
	public DatabaseController getDBController() {
		return this.dbController;
	}
	
	/**
	 * Create the application.
	 */
	public MainWindow(DatabaseController dbController) {
		this.dbController = dbController;
		initialize();
		this.frmWebServiceRequirements.setVisible(true);
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frmWebServiceRequirements = new JFrame();
		frmWebServiceRequirements.setTitle("Web Service Requirements");
		frmWebServiceRequirements.setBounds(100, 100, 855, 630);
		frmWebServiceRequirements.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		JMenuBar menuBar = new JMenuBar();
		frmWebServiceRequirements.setJMenuBar(menuBar);
		
		JMenu createMenu = new JMenu("Create");
		menuBar.add(createMenu);
		
		JMenuItem mntmInitialOnto = new JMenuItem("Initial Ontology");
		mntmInitialOnto.addActionListener(this);
		createMenu.add(mntmInitialOnto);
		
		JMenuItem mntmGoalOnto = new JMenuItem("Goal Ontology");
		mntmGoalOnto.addActionListener(this);
		createMenu.add(mntmGoalOnto);
		
		frmWebServiceRequirements.getContentPane().setLayout(new GridLayout(1, 0, 0, 0));
		
		mainPanel = new MainPanel(this);
		frmWebServiceRequirements.getContentPane().add(mainPanel);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		List<MyOWLClass> classes =  this.mainPanel.getOwlClassesList();
		List<MyOWLObjectProperty> objProperties = this.mainPanel.getObjectPropertyList();
		List<MyOWLDataProperty> dataProperties = this.mainPanel.getDataPropertyList();
		List<MyOWLIndividual> individuals = this.mainPanel.getIndividualsList();
		try {
			logger.debug("Creating ontology");
			AddInputDialog dia = new AddInputDialog("Insert name of Ontology: ");
			String ontologyName = dia.getOutput();
			this.onotoName = new OWLCreationManager(ontologyName).createOntology(classes, objProperties, dataProperties, individuals);
			//store onto to DB
			DataManipulator manipulatorExpec = new DBExpectationsManipulator(dbController, onotoName, EnumUtils.INITIAL);
			manipulatorExpec.insert();
			//get id of current stored expectations - as ontology
			int expectationsID = ((DBExpectationsManipulator)manipulatorExpec).getId();
			
			logger.debug("Ontology created");
			
			//insert attributes from which ontology was created to DB
			DataManipulator manipulatorCl = new DBAttributesManipulator(dbController, new AttributesMapper().mapAttributesFromOWL(classes), expectationsID);
			manipulatorCl.insert();
			DataManipulator manipulatorOp = new DBAttributesManipulator(dbController, new AttributesMapper().mapAttributesFromOWL(objProperties), expectationsID);
			manipulatorOp.insert();
			DataManipulator manipulatorDp = new DBAttributesManipulator(dbController, new AttributesMapper().mapAttributesFromOWL(dataProperties), expectationsID);
			manipulatorDp.insert();
			DataManipulator manipulatorIndi = new DBAttributesManipulator(dbController, new AttributesMapper().mapAttributesFromOWL(individuals), expectationsID);
			manipulatorIndi.insert();
			logger.debug("Attributes were stored in DB");
		} catch (OWLOntologyCreationException e1) {
			logger.error("Error during ontology creation!!!");
			e1.printStackTrace();
		} catch (OWLOntologyStorageException ex) {
			logger.error("Error during saving ontology!!!");
			ex.printStackTrace();
		} catch (IOException ef) {
			logger.error("Error during temp file creation!");
			ef.printStackTrace();
		} catch (SQLException eq) {
			logger.error("Error during storing data to DB");
			if (dbController.getCon() != null) {
	            try {
	            	logger.error("Transaction is being rolled back");
	            	dbController.getCon().rollback();
	            	dbController.getCon().setAutoCommit(true);
	            } catch(SQLException excep) {
	            	logger.error("Error during rolled back");
	            }
	        }
			eq.printStackTrace();
		}
	}
}
